﻿// Copyright 2012 T4C: sejerpz@gmail.com
// Licensed under GPL v3

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SET.Core;

namespace SET
{
    public partial class FormStatisticsDetails : Form
    {
        private FormStatisticsDetails()
        {
            InitializeComponent();
        }

        public FormStatisticsDetails(string periodDescription, DataTable data)
            : this()
        {
            this.Text = string.Format(Messages.ResourceManager.GetString("Details exercise {0} for period: {1}".ToValidIdentifier()),
                Messages.ResourceManager.GetString(Excercise.Intervals.ToString().ToValidIdentifier()),
                periodDescription);
            labelResults.Text += " " + periodDescription;
            dataGridViewDetails.DataSource = data;
            UpdateGraphicsData(data);
        }

        private void UpdateGraphicsData(DataTable data)
        {
            var responses = new int[12, 2];

            foreach (DataRow row in data.Rows)
            {
                string correctAnswer = TryGet<string>(row, "CorrectAnswer");
                string userAnswer = TryGet<string>(row, "UserAnswer");

                int interval;

                if (int.TryParse(correctAnswer, out interval))
                {
                    interval--; // the array is base 0
                    responses[interval, 0] += 1;
                    if (string.Compare(correctAnswer, userAnswer, true) == 0)
                        responses[interval, 1] += 1;
                }
            }

            for (int i = 0; i < responses.GetLength(0); i++)
            {
                var label = (Label)tableLayoutPanelGraphicalData.Controls[string.Format("labelInterval{0}", i + 1)];
                var progress = (ProgressBar)tableLayoutPanelGraphicalData.Controls[string.Format("progressBarInterval{0}", i + 1)];
                bool enabled = responses[i, 0] > 0;

                if (enabled)
                {
                    progress.Value = responses[i, 1] * 100 / responses[i, 0];
                    toolTips.SetToolTip(progress, string.Format(Messages.ResourceManager.GetString("Correct answers {0} of {1}".ToValidIdentifier()), responses[i, 1], responses[i, 0]));
                }
                else
                {
                    toolTips.SetToolTip(progress, "");
                }

                label.Enabled = enabled;
                progress.Enabled = enabled;
            }
        }

        private T TryGet<T>(DataRow row, string columnName, T defaultValue = default(T))
        {
            object value = row[columnName];
            if (value == null || value == DBNull.Value)
                return defaultValue;

            return (T)value;
        }
    }
}
